package cn.com.zetatech.maple.parser.processor.impl;

import cn.com.zetatech.maple.entity.Field;
import cn.com.zetatech.maple.entity.Rule;
import cn.com.zetatech.maple.parser.processor.LineProcessor;
import cn.com.zetatech.maple.parser.utils.ScriptEnginePool;
import org.apache.commons.lang3.StringUtils;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author cheng.cao@zetatech.com.cn
 */
@SuppressWarnings("all")
public class SimpleLineProcessor implements LineProcessor<Map<String, String>> {

    @Override
    public Map<String, String> processLine(File file, String line, Rule rule) throws IOException {
        String[] items = null;
        if (rule.getItemSize() <= 0) {
            items = line.split(rule.getSeparator());
        } else {
            items = line.split(rule.getSeparator(), rule.getItemSize());
        }
        String itemReplace = rule.getItemReplace();
        Map<String, String> result = new HashMap<>();

        for (Field field : rule.getFields()) {
            if (field.isIgnore()) {
                continue;
            }
            String staticValue = field.getValue();
            String property = field.getProperty();
            String script = field.getScript();
            String column = field.getColumn();

            int index = Integer.valueOf(property);
            if (index < 0) {
                if (staticValue != null) {
                    if (staticValue.contains("${file_name}")) {
                        staticValue = staticValue.replace("${file_name}#", "");
                        Pattern pattern = Pattern.compile(staticValue);
                        Matcher m = pattern.matcher(file.getAbsolutePath());
                        if (m.find()) {
                            result.put(column, m.group());
                        }
                    } else {
                        // 认为是固定值
                        result.put(column, staticValue);
                    }
                }
            } else {
                result.put(column, items[index]);
            }

            if (result.get(column) != null && itemReplace != null) {
                String processResult = result.get(column).replaceAll(itemReplace, "");
                result.put(column, processResult);
            }

            // 调用脚本处理后续逻辑
            if (StringUtils.isNotBlank(script)) {
                String engineName = field.getScriptEngine();
                // 默认脚本引擎:groovy
                if (engineName == null || "".equalsIgnoreCase(engineName.trim())) {
                    engineName = "groovy";
                }
                ScriptEngine engine = ScriptEnginePool.getEngine(engineName.toLowerCase());
                Bindings bindings = engine.createBindings();
                bindings.put("fieldVal", result.get(column));
                bindings.put("line", line);
                bindings.put("file", file.getAbsolutePath());
                try {
                    String processResult = (String) engine.eval(script, bindings);
                    result.put(column, processResult);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

}
